<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>面向对象</title>
  </head>
  <body>
    <script type="text/javascript">
      /**
       * 借助构造函数实现继承
       */
      function Parent1() {
        this.name = "parent1";
      }
      Parent1.prototype.say = function () {};
      function Child1() {
        Parent1.call(this);
        this.type = "child1";
      }
      console.log(new Child1());

      // 获取不到父原型对象上的 say()方法
      // console.log(new Child1().say());

      /**
       * 借助原型链实现继承
       */
      function Parent2() {
        this.name = "parent2";
        this.play = [1, 2, 3];
      }
      function Child2() {
        this.type = "child2";
      }
      Child2.prototype = new Parent2();

      var s1 = new Child2();
      var s2 = new Child2();
      console.log(s1.play, s2.play);
      s1.play.push(4);

      // new出来的两个实例其父构造器下的属性值 会同步
      // [1, 2, 3, 4]   [1, 2, 3, 4]
      console.log(s1.play, s2.play);

      /**
       * 组合方式
       */
      function Parent3() {
        console.log("function Parent3...");
        this.name = "parent3";
        this.play = [1, 2, 3];
      }
      function Child3() {
        Parent3.call(this);
        this.type = "child3";
      }
      Child3.prototype = new Parent3();
      var s3 = new Child3();

      // Parent3.call(this) 和  new Parent3()  父级构造函数 会执行了两次

      /**
       * 组合继承的优化1
       */
      function Parent4() {
        this.name = "parent4";
        this.play = [1, 2, 3];
      }
      function Child4() {
        Parent4.call(this);
        this.type = "child4";
      }
      Child4.prototype = Parent4.prototype;
      var s5 = new Child4();

      console.log(s5 instanceof Child4, s5 instanceof Parent4);
      console.log(s5.constructor); // Parent4
      //  实例对象s5 = new Child4()的构造器 constructor 应该为 Child4

      /**
       * 组合继承的优化2
       */
      function Parent5() {
        this.name = "parent5";
        this.play = [1, 2, 3];
      }
      function Child5() {
        Parent5.call(this);
        this.type = "child5";
      }
      //   Object.create(obj)方法创建一个新对象，使用现有的对象来提供新创建的对象的__proto__
      let obj = Object.create(Parent5.prototype);
      console.log('Object.create(Parent5.prototype)',obj);
      Child5.prototype = obj;
      Child5.prototype.constructor = Child5;
      console.log(
        "一条原型链 ",
        Child5.prototype.__proto__ === obj.__proto__,
        obj.__proto__ === Parent5.prototype
      );

      var s7 = new Child5();
      console.log(
        "即是子类也是父类的实例",
        s7 instanceof Child5,
        s7 instanceof Parent5
      );
      console.log(s7.constructor);
    </script>
  </body>
</html>
